from bson.objectid import ObjectId
import pymongo

u = {
    u'spreader_id': u'59e33b587cf16839d08a7234',
    u'superior_spreader_id': u'59e2da447cf16839d08a7219',
    u'top_spreader_id': u'59e2da447cf16839d08a7229',
    u'spread_level': 2,
    u'spread_consumption_amount': 1999.0, u'bonus_points': 1999.0,
    u'spread_bonus_points': 1999.0,
    u'spread_bonus_points_take_effect_time': 1511578227,
    u'vendor_id': u'59e2da447cf16839d08a7219',
    u'consumption_amount': 1999.0,

    u'specifics': {
        'user_id': 'USER_ID',
        'vendor_id': 'VENDOR_ID',  # 厂商，用于在用户端获取 product list
        'spreader_id': 'SPREADER_ID',  # 推广者
        'superior_spreader_id': 'SUPERIOR_SPREADER_ID',  # 上级推广者
        'top_spreader_id': 'TOP_SPREADER_ID',  # 顶级推广者
        'spread_level': 2,  # 推广级别，推广者级别+1

        'bonus_points': 100,  # 消费积分
        'spread_bonus_points': 100,  # 在推广体系下的消费积分
        'spread_bonus_points_take_effect_time': 1507688882,  # 推广积分生效时间，从0发生变化时记录下来的时间，用于计算佣金
        'consumption_amount': 100,  # 消费总金额
        'spread_consumption_amount': 100,  # 在推广体系下的消费总金额
    },

    u'username': u'15277948056',
    u'weixin': {u'mp': {u'openid': u'oz7vx0Woq7VbXBhlVIIMoAvuo4DU'}},
    u'app_id': u'120FFFC42C26B484EBD28DD9263B3581',
    u'phone': u'15277948056',
    u'avatar': u'http://wx.qlogo.cn/mmopen/vi_32/YM0RUfjdfbfbyee8qR54ic0Rz89EH3WTmbWmVkzQV7sxjWdM5NstxdqZkOormd071ZBrRyD6IFDq5xibI6TZyJYA/0',
    u'user_no': 519868161384L,
    u'_id': ObjectId('5a16436797c2092ae15011e9'),
    u'nickname': u'\u30fd',
}

o = {
    u'vid': u'59e2da447cf16839d08a7219',
    u'sid': u'59e2da447cf16839d08a7219',
    u'spread_total_price': 2980.0,
    u'spread_bonus_points': 2980.0,
    u'bonus_points': 2980.0,
    u'commission_s': 625.8,
    u'commission_ss': 268.2,
    u'commission_ts': 0.0,

    u'specifics': {
        'vid': 'VENDOR_ID',
        'sid': 'SPREADER_ID',  # 推广者
        'ssid': 'SUPERIOR_SPREADER_ID',  # 上级推广者
        'tsid': 'TOP_SPREADER_ID',  # 顶级推广者

        'spread_bonus_points': 100,
        'spread_total_price': 100,
        'bonus_points': 100,

        'total_price': 100,

        'commission_s': 15,
        'commission_ss': 9,
        'commission_ts': 6,
        'commission': 15,  # for spreader

        'products': [
            {
                'product_id': 'PID',  # product_id, 具体购买的产品
                # 'did': 'DID',  # device_id, 标识在哪台设备上产生的消费，如为设备服务续期
                # 'type': 'service|goods',  # 标识该商品为 service or not
                'unit_price': 69.9,  # 当时消费单价（商品价格会有变化，账单需要记录购买时的单价）
                'quantity': 2,  # 购买数量
                # 'percentages': [10, 15, 9, 6],  # 记录当时系统分成比例设置，数组中元素分别是经销商，消费者，推广者以及上级推广者的分成比例，
                'specifics': {
                    'device_id': 'DID',  # 标识该商品（服务）是为哪台设备（模块）购买
                    'city': 'Zhuhai',  # 设备所属的区域，用于过滤出相关用户列表以及统计区域消费情况等
                    'district': 'Xiangzhou',
                },
            },
        ]
    },

    u'status': u'to_be_paid',
    u'total_price': 2980.0,
    u'products': [
        {
            u'product_id': u'59e2ea517cf16839d08a7228',
            u'unit_price': 2980.0,
            u'quantity': 1,
        }
    ],
    u'created_time': 1516860207,
    u'deliver_address': {
        u'postalcode': u'0',
        u'phone': u'3668558690',
        u'consignee': u'2728669878',
        u'detail': u'56586586654598844769885',
        u'area': u''
    },
    u'order_no': u'77327036166598237355',
    u'_id': ObjectId('5a69732f97c2090d07605b14'),
    u'uid': u'59e6aa897cf16809b662b489',
}

p = {
    u'name': u'A16',
    u'tags': u'A16, \u9500\u552e\u578b, \u514d\u5b89\u88c5, \u51c0\u6c34\u673a',

    # ???
    u'percentages': [15, 9, 6],

    u'desc_url': u'',
    u'preview_url': u'',
    u'unit_price': 2980,
    u'notify_url': u'www.baidu.com', u'uid': u'58e5c14d7cf1680c27f2cafc',
    u'_id': ObjectId('59b88ef37cf168223192f00d'),
    u'desc': u'\u514d\u5b89\u88c5\u667a\u80fd\u51c0\u6c34\u673a(\u9500\u552e\u578b)',

    u'specifics': {
        'percentages': [15, 9, 6],  # 商品分成比例
        'bonus_points_unit': 1,  # 一块钱积一分
        'bonus_points_multiple': 1,  # 积分倍数
        'increase_spread_bonus_points': True,  # 是否增加用户的推广积分
        'recharge_days': 90,

        u'vof': {
            u'vof': [75, 75, 75, 75]
        },
        u'attr': {
            u'flowmeter': {
                u'vof': [60, 75, 65, 60],
                u'metering': 1
            },
            u'mode': 2,
            u'filters': [
                {u'seq': 1, u'name': u'PP\u68c9\u6ee4\u82af', u'srvc_life': 4320, u'work_life': 540},
                {u'seq': 2, u'name': u'\u6d3b\u6027\u70ad\u6ee4\u82af', u'srvc_life': 8640, u'work_life': 1080},
                {u'seq': 3, u'name': u'RO\u53cd\u6e17\u900f\u6ee4\u82af', u'srvc_life': 17280, u'work_life': 2160}
            ]
        }
    },
}

d = {
    u'module_vendor_id': u'59c0885b7cf168614886fd8c',
    u'vendor_id': u'59c0885b7cf168614886fd8c',
    u'qc_id': u'59c0885b7cf168614886fd8c',
    u'online_at': 1509076821,
    u'offline_at': 1509077350,
    u'batch_no': u'20170925',
    u'model': u'A16',
    u'_id': ObjectId('59ca77697cf16815acbdb6aa'),
    u'device_id': u'8D804CE1BB800303',
    u'type': u'WPM',
    u'module_model': u'Hi260',
    u'product_id': u'59e2ea517cf16839d08a7228',
    u'module_batch_no': u'20170925',

    u'specifics': {
        u'wpm_stat': {
            u'stat': 37, u'otmp': 28, u'itds': 0, u'itmp': 27, u'otds': 0, u'usmd': 1
        },
        u'wpm_filter': {
            u'ftwk02': 1, u'ftwk03': 1, u'ftwk01': 1, u'ftwk04': 0, u'ftwk05': 0, u'ftpw05': 0,
            u'ftpw04': 0, u'ftpw03': 1, u'ftpw02': 1, u'ftpw01': 1
        },
        u'wpm_misc': {
            u'ver': u'1.2.3', u'project': u'HFS0108WPS', u'platform': u'Hi260',
            u'api': u'iot.hifocus.cn', u'build': u'20170929', u'con': u'WIFI'
        },
    },
}

user_fields = ['vendor_id', 'spreader_id', 'superior_spreader_id', 'top_spreader_id', 'spread_level', 'bonus_points',
               'spread_bonus_points',
               'spread_bonus_points_take_effect_time', 'consumption_amount', 'spread_consumption_amount']

order_fields = [
    'vid', 'sid', 'ssid', 'tsid', 'spread_bonus_points', 'spread_total_price', 'uid',
    'bonus_points', 'total_price', 'commission_s', 'commission_ss', 'commission_ts', 'commission',
]

product_fields = [
    'percentages', 'bonus_points_unit', 'increase_spread_bonus_points', 'bonus_points_multiple', 'uid',
]


def func(specifics, a, fields):
    for f in fields:
        if f in a:
            specifics.update({f: a.pop(f)})


# 使用 mongo 客户端做数据库复制
# $ mongo
# > db.dropDatabase('bora_v2')
# > db.copyDatabase('bora', 'bora_v2')

db = pymongo.MongoClient().bora_v2
c = db.users
for a in c.find():
    specifics = a['specifics'] if 'specifics' in a else dict()
    specifics.update(user_id=str(a['_id']))
    func(specifics, a, user_fields)
    c.update_one({'_id': a['_id']}, {'$set': {'specifics': specifics}})

c = db.orders
for a in c.find():
    specifics = a['specifics'] if 'specifics' in a else dict()
    specifics.update(uid=a['uid'])
    func(specifics, a, order_fields)
    c.update_one({'_id': a['_id']}, {'$set': {'specifics': specifics}})

c = db.products
for a in c.find():
    specifics = a['specifics'] if 'specifics' in a else dict()
    specifics.update(uid=a['uid'])
    func(specifics, a, product_fields)
    c.update_one({'_id': a['_id']}, {'$set': {'specifics': specifics}})

dgk_x = {
    "username": "18923365099",
    "weixin": {
        "mp": {
            "openid": "oz7vx0buPKl3XYR0hDW89CnkqqSM"
        }
    },
    "vendor_id": "59e2da447cf16839d08a7219",
    "app_id": "120FFFC42C26B484EBD28DD9263B3581",
    "spread_level": 1,
    "phone": "18923365099",
    "specifics": {
        "vendor_id": "59e2da447cf16839d08a7219",
        "user_id": "59e9a1c97cf16809b662c2e1",
        "spread_level": 1,
        "spreader_id": "59e2da447cf16839d08a7219"
    },
    "avatar": "http://wx.qlogo.cn/mmopen/vi_32/3oRvdnnHia4c9FBaiazzpKo76bzfibkk4OOeLnx4ia8qKcVZiarFLyzWUY96tPicIz0WrV18HRmEo0DDZOKeSzC9fIqw/0",
    "user_no": 756193802642,
    "spreader_id": "59e2da447cf16839d08a7219",
    "nickname": "海富思科技谢工"
}
# -->
dgk_m = {
    # "_id": ObjectId("59c0885b7cf168614886fd8c"),
    "spread_bonus_points": 3.0799999999999983,
    "name": "Vendor",
    "phone": "13926950001",
    "weixin": {
        "mp": {
            "openid": "oPDmD0f__9NKOQ4Hr3WCKwDt2Ghc"
        }
    },
    "spread_bonus_points_take_effect_time": 1507821081,
    "vendor_id": "59c0885b7cf168614886fd8c",
    "app_id": "120FFFC42C26B484EBD28DD9263B3581",
    "consumption_amount": 9.039999999999997,
    "bonus_points": 3.0799999999999983,
    "specifics": {
        "user_id": "59c0885b7cf168614886fd8c",
        "spread_consumption_amount": 3.0799999999999983,
        "spread_bonus_points_take_effect_time": 1507821081,
        "vendor_id": "59c0885b7cf168614886fd8c",
        "spread_bonus_points": 3.0799999999999983,
        "bonus_points": 3.0799999999999983,
        "consumption_amount": 9.039999999999997
    },
    "avatar": "http://wx.qlogo.cn/mmopen/vi_32/BWcd34S0qHLys6AV8BrEdDE0aHvIU1HenUYVoicRhAiavq6yjRIvkCwOmok7yVs6FaiaBWBlSYV0Picz8NlXBnASbg/0",
    "user_no": 564777241034,
    "address": "NaN...",
    "password": "52c69e3a57331081823331c4e69d3f2e",
    "nickname": "IoT Intelligence Platform",
    "email": "marvin.nps@gmail.com",
    "spread_consumption_amount": 3.0799999999999983
}
#################
sdw_x = {
    "username": "18923365099",
    "weixin": {
        "mp": {
            "openid": "oPDmD0b2S9JuSYGdnHcljhHPFZXA"
        }
    },
    "vendor_id": "5a0ec9d27cf1682a17b5788d",
    "app_id": "89CF7BCE962A89EA77FE56EC7CA7A2FF",
    "spread_level": 1,
    "phone": "18923365099",
    "specifics": {
        "vendor_id": "5a0ec9d27cf1682a17b5788d",
        "user_id": "5a12255a7cf168797664a259",
        "spread_level": 1,
        "spreader_id": "5a0ec9d27cf1682a17b5788d"
    },
    "avatar": "http://wx.qlogo.cn/mmopen/vi_32/ne9pJjLvtYgZIBqnpxuljIQbP8CGjEGJzlfAA3RibwVXYYo5xUT3bfp44Nac9icI824PanzjiaJIqL9uabzsvbfIQ/0",
    "user_no": 238310691238,
    "spreader_id": "5a0ec9d27cf1682a17b5788d",
    "nickname": "海富思科技谢工"
}
# -->
sdw_m = {
    "username": "13926950001",
    "superior_id": "5a587904d823ef4e582422e4",
    "spread_bonus_points": 0.01,
    "name": "IoT Platform",
    "roles": [
        "5a588462d823ef7c851c6ecf"
    ],
    "phone": "13926950001",
    "weixin": {
        "mp": {
            "openid": "oPDmD0f__9NKOQ4Hr3WCKwDt2Ghc"
        }
    },
    "spread_bonus_points_take_effect_time": 1510935028,
    "vendor_id": "5a0ec9d27cf1682a17b5788d",
    "app_id": "89CF7BCE962A89EA77FE56EC7CA7A2FF",
    "consumption_amount": 0.02,
    "bonus_points": 0.02,
    "specifics": {
        "user_id": "5a0ec9d27cf1682a17b5788d",
        "spread_consumption_amount": 0.01,
        "spread_bonus_points_take_effect_time": 1510935028,
        "vendor_id": "5a0ec9d27cf1682a17b5788d",
        "spread_bonus_points": 0.01,
        "bonus_points": 0.02,
        "consumption_amount": 0.02
    },
    "avatar": "http://wx.qlogo.cn/mmopen/vi_32/BWcd34S0qHLys6AV8BrEdDE0aHvIU1HenUYVoicRhAiavq6yjRIvkCwOmok7yVs6FaiaBWBlSYV0Picz8NlXBnASbg/0",
    "user_no": 575625380713,
    "password": "52c69e3a57331081823331c4e69d3f2e",
    "nickname": "IoT Intelligence Platform",
    "spread_consumption_amount": 0.01
}


def extract_fields(src, required_fields=None, optional_fields=None):
    result = {}
    if required_fields is not None:
        for f in required_fields:
            result[f] = src[f]
    if optional_fields is not None:
        for f in optional_fields:
            if f in src:
                result[f] = src[f]
    return result


app_ids = ['89CF7BCE962A89EA77FE56EC7CA7A2FF', '120FFFC42C26B484EBD28DD9263B3581']
app_ids = ['120FFFC42C26B484EBD28DD9263B3581']

fields = ['username', 'phone', 'weixin', 'avatar', 'user_no', 'nickname']
# unset password
for aid in app_ids:
    filter_cond = {'username': '18923365099', 'app_id': aid}
    u.update_one(filter_cond, {'$set': {'password': '19ccb94a95b912bbf315461b686c1a7d'}})
    a = u.find_one(filter_cond)
    print a
    a = extract_fields(a, fields)
    u.delete_one(filter_cond)
    u.update_one({'phone': '13926950001', 'app_id': aid}, {'$set': a, '$unset': {'password': 0}})

for aid in app_ids:
    filter_cond = {'username': '18923365099', 'app_id': aid}
    a = u.find_one_and_update(filter_cond, {'$unset': {'email': 0}})
    a.pop('_id')
    pr_obj(a)
